package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.user.UserConstants.AdminConstants;
import com.heima.common.exception.CostomException;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.feign.ApAuthorFeign.ArticleFeign;
import com.heima.user.feign.WmUserFeign.WemediaFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    ArticleFeign articleFeign;

    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //1.检查参数
        if(dto == null ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页检查
        dto.checkParam();

        //2.根据状态分页查询
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper();
        if(dto.getStatus() != null){
            lambdaQueryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        //分页条件构建
        IPage pageParam = new Page(dto.getPage(),dto.getSize());
        IPage page = page(pageParam, lambdaQueryWrapper);

        //3.返回结果
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }


    /**
     * 修改用户认证信息
     * @param dto
     * @param code
     * @return
     */
    @GlobalTransactional
    @Override
    public ResponseResult updateStatusById(AuthDto dto,Short code) {
        //首先判断参数是否为空
        if (dto==null||dto.getId()==null||code==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //修改认证信息
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setStatus(code);
        apUserRealname.setId(dto.getId());
        if (dto.getMsg()!=null){
            apUserRealname.setReason(dto.getMsg());
        }

        //此方法 在修改时 只是根据id修改设置进去的值 那些没有设置数据的成员变量如果为null 不会去覆盖数据库原有字段的内容
        updateById(apUserRealname);

        //code是Short类型 比较内容必须用eq比较   ==比较的是地址值
        if (code.equals(AdminConstants.PASS_AUTH)){
            //如果传来的状态为通过 就调用方法去创建自媒体人  可以抽取出来 先调用查询 没有的话 在添加
            ApUserRealname userRealname = getById(dto.getId());
            ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
            if (apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            ResponseResult result = createWemedia(apUser);
            if (result.getCode()!=0){
                throw new CostomException(ResponseResult.errorResult(AppHttpCodeEnum.AUTH_FAIL));
            }
            apUser.setFlag((short)1);
            apUserMapper.updateById(apUser);
            return result;
        }

        //全部完成后返回ok
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    public ResponseResult createWemedia(ApUser apUser){
        WmUser wmuser = wemediaFeign.findByName(apUser.getName());

        if (wmuser ==null){

            //用来测试分布式事务
            // int a = 1/0;

            wmuser = new WmUser();
            wmuser.setApUserId(apUser.getId());
            wmuser.setName(apUser.getName());
            wmuser.setPassword(apUser.getPassword());
            wmuser.setSalt(apUser.getSalt());
            wmuser.setPhone(apUser.getPhone());
            wmuser.setStatus(9); // 9代表正常使用状态
            wmuser.setCreatedTime(new Date());
            ResponseResult wmUserResult = wemediaFeign.save(wmuser);

            WmUser byName = wemediaFeign.findByName(apUser.getName());
            Integer wmUserId = byName.getId();
            return createAuth(apUser,wmUserId);
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
    }




    public ResponseResult createAuth(ApUser apUser,Integer wmUserId){

        ApAuthor apAuthor = articleFeign.findByUserId(apUser.getId());

        if (apAuthor == null){
            apAuthor = new ApAuthor();
            apAuthor.setName(apUser.getName());
            apAuthor.setType(AdminConstants.AUTH_TYPE);  // 2代表该作者的类型是平台自媒体人
            apAuthor.setUserId(apUser.getId());
            apAuthor.setCreatedTime(new Date());
            apAuthor.setWmUserId(wmUserId);
            articleFeign.save(apAuthor);

            ApAuthor byUserId = articleFeign.findByUserId(apUser.getId());
            Integer apAuthorId = byUserId.getId();

            WmUser byName = wemediaFeign.findByName(apUser.getName());
            byName.setApAuthorId(apAuthorId);
            return wemediaFeign.updateByAuthorId(byName);

        }

        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
    }


}